package cn.wolfcode.trip.base.service.impl;

import cn.wolfcode.trip.base.domain.Travel;
import cn.wolfcode.trip.base.domain.TravelContent;
import cn.wolfcode.trip.base.mapper.TravelContentMapper;
import cn.wolfcode.trip.base.mapper.TravelMapper;
import cn.wolfcode.trip.base.query.TravelQueryObject;
import cn.wolfcode.trip.base.service.ITravelService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;

@Service
public class TravelServiceImpl implements ITravelService {

    @Autowired
    private TravelMapper travelMapper;
    @Autowired
    private TravelContentMapper travelContentMapper;

    /**
     * 游记分页加高级查询
     *
     * @param qo
     * @return
     */
    public PageInfo queryForList(TravelQueryObject qo) {
        PageHelper.startPage(qo.getCurrentPage(), qo.getPageSize(), qo.getOrderBy());
        return new PageInfo(travelMapper.queryForList(qo));
    }

    /**
     * 保存游记
     *
     * @param travel
     */
    public void save(Travel travel) {
        Date date = new Date();
        //设置创建游记时间
        travel.setCreateTime(date);
        //设置最后更新时间
        travel.setLastUpdateTime(date);
        travelMapper.insert(travel);
        //保存游记内容
        TravelContent travelContent = travel.getTravelContent();
        //主键关联
        travelContent.setId(travel.getId());
        travelContentMapper.insert(travelContent);
    }

    /**
     * 查询当前点击游记,用于回显
     *
     * @param id
     * @return
     */
    public Travel getById(Long id) {
        return travelMapper.selectByPrimaryKey(id);
    }

    /**
     * 更新游记操作
     *
     * @param travel
     */
    public void update(Travel travel) {
        //设置最后更新时间
        travel.setLastUpdateTime(new Date());
        travelMapper.updateByPrimaryKey(travel);
        //更新游记内容
        TravelContent travelContent = travel.getTravelContent();
        travelContent.setId(travel.getId());//主键关联
        travelContentMapper.updateByPrimaryKey(travelContent);
    }

    /**
     * 待审核游记查看游记内容
     *
     * @param id
     * @return
     */
    public TravelContent getContentById(Long id) {
        return travelContentMapper.selectByPrimaryKey(id);
    }

    /**
     * 更改待审核游记状态为发布和拒绝
     *
     * @param travel
     */
    public void changeState(Travel travel) {
        //如果是已发布状态,就设置发布时间
        if (travel.getState() == Travel.STATE_RELEASE) {
            travel.setReleaseTime(new Date());
        }
        travelMapper.changeState(travel);
    }

    public void delete(Long id) {
        travelMapper.deleteByPrimaryKey(id);
    }

    public List<Travel> selectRelease(Long id) {
        return travelMapper.selectRelease(id);
    }
}
